package com.chongbangbang.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;


/**
 * Druid的配置
 *  访问路径 ： localhost:8080/druid
 */


@Configuration
public class DruidConfig {

    @Primary
    @Bean
    @ConfigurationProperties("spring.datasource.druid")
    public DataSource dataSourceOne(){
        return DruidDataSourceBuilder.create().build();
    }

    // 后台监控(只需要调用即可)
    // SpringBoot内置了servlet容器,所有没有web.xml, 替代方法: ServletRegistrationBean
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        // 后台登录密码设置
        HashMap<String, String> initParams = new HashMap<>();
            // 配置(loginUsername, loginPassword等所有key是设死的)
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "123456");

            // 谁可以访问("": 所有人, "localhost":本机(出错了,好像不行), "ip": 该ip可以访问)
        initParams.put("allow","");
            // 也可以配谁禁止访问
        //initParams.put("mubei", "端口");
//        initParams.put("TT233", "120.25.237.214");

        bean.setInitParameters(initParams);

        return bean;
    }

    // filter
    // 同理.要替代web.xml, 需要FilterRegistrationBean
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {

        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());

        HashMap<String, String> initParams = new HashMap<>();
        // 不过滤哪些请求
        initParams.put("exclusions", "*.js,*.css,/druid/**");

        bean.setInitParameters(initParams);
        return bean;
    }
}
